<?php
namespace App\Service\Admin;

use Illuminate\Support\Facades\DB;

class IndexService extends BaseService
{
    /**
     * 后台登录
     * @param string $uname 账户名
     * @param string $upwd 密码
     */
    public function dologin($uname, $upwd)
    {
        $res = (array) DB::table($this->dbAdmin)->where('name', $uname)->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '账号不存在');
        }
        if ($res['password'] != md5($upwd)) {
            return array('code' => -2, 'msg' => '密码错误');
        }
        if ($res['id'] != 1) {
            $authOne = (array) $this->dbConn($this->dbAuth)
                ->where('del', 0)
                ->where('admin_id', $res['id'])
                ->orderBy('id', 'desc')
                ->first();
            if (empty($authOne)) {
                return $this->toback(-2, '没有权限，请联系后台');
            }
        }
        //登录日志
        $token = md5(time());
        $logData = [
            'adminid' => $res['id'],
            'admin_name' => $res['name'],
            'token' => $token,
            'addtime' => toDate(),
        ];
        DB::table($this->dbAdLogin)->insertGetId($logData); //日志
        DB::table($this->dbAdmin)->where('id', $res['id'])->update(['lasttime' => toDate()]); //最近登录
        //返回值
        $resData = [
            'adminName' => $res['name'],
            'token' => $token,
        ];
        return array('code' => 0, 'msg' => 'success', 'data' => $resData);
    }

    //登录日志
    public function getLoginLog($token, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $adminOne = (array) DB::table($this->dbAdLogin)
            ->where('token', $token)
            ->orderBy('id', 'desc')
            ->first();
        if (empty($adminOne)) {
            return array('code' => -2, 'msg' => '没有登录');
        }
        $adminid = $adminOne['adminid'];
        $db = DB::table($this->dbAdLogin)->where('adminid', $adminid);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        return array('code' => 0, 'msg' => 'success', 'data' => $res, 'total' => $total);
    }

    //验证登录
    public function checkLogin($token)
    {
        $res = (array) DB::table($this->dbAdLogin)->where('token', $token)->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '没有登录');
        }
        return array('code' => 0, 'msg' => '已登录');
    }

    //后台菜单
    public function getLeftMenu($aid)
    {
        $ids = [];
        if ($aid > 1) {
            $authOnes = $this->dbConn($this->dbAuth)
                ->where('del', 0)
                ->where('admin_id', $aid)
                ->get();
            if (!count($authOnes)) {
                return $this->toback(-2, '没有权限');
            }
            foreach ($authOnes as $v) {
                $v = (array) $v;
                $ids[] = $v['action_id'];
            }
        }
        $db = DB::table($this->dbAction)
            //->select('id', 'title', 'icon', 'link', 'pid')
            ->where('del', 0)
            ->where('pid', 0);
        if ($ids) {
            $db = $db->whereIn('id', $ids);
        }
        $res = $db->orderBy('sort', 'desc')->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有菜单');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $childArys = [];
            $db2 = DB::table($this->dbAction)
                ->select('id', 'title', 'link')
                ->where('del', 0)
                ->where('pid', $v['id']);
            if ($ids) {
                $db2 = $db2->whereIn('id', $ids);
            }
            $childOnes = $db2->orderBy('sort', 'desc')->get();
            if (count($childOnes)) {
                foreach ($childOnes as $vv) {
                    $vv = (array) $vv;
                    $childArys[] = [
                        'id' => $vv['id'],
                        'title' => $vv['title'],
                        'link' => $vv['link'],
                    ];
                }
            }
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'icon' => $v['icon'],
                'link' => $v['link'],
                'childs' => $childArys,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    //首页统计
    public function tongji()
    {
        //获取配置
        $config = $this->getConfig('retail_inventory_warning');
        $scyj = $config['code']==0 ? $config['data'] : 0;
        $config = $this->getConfig('Channel_inventory_warning');
        $qdyj = $config['code']==0 ? $config['data'] : 0;
        //库存预警
        $scStock = $this->dbConn($this->dbGsku)
            ->where('del', 0)
            ->where('stock', '<', $scyj)
            ->count();
        $qdStock = $this->dbwbConn($this->dbQdGsku)
            ->where('del', 0)
            ->where('stock', '<', $qdyj)
            ->count();
        $arys = [
            'userNum' => $this->dbConn($this->dbUser)->count(),
            'scGoodsNum' => $this->dbConn($this->dbGoods)->where('del', 0)->count(),
            'scGsaleNum' => $this->dbConn($this->dbGoods)
                ->where('del', 0)
                ->where('is_shelf', 1)
                ->count(),
            'scOrderNum' => $this->dbConn($this->dbOrder)->where('del', 0)->count(),
            'scVisitNum' => $this->dbConn($this->dbUtrace)->count(),
            'scOrderPaynoNum' => $this->dbConn($this->dbOrder)
                ->where('del', 0)
                ->where('iscancel', 1)
                ->where('status', 1)
                ->count(),
            'scOrderSendnoNum' => $this->dbConn($this->dbOrder)
                ->where('del', 0)
                ->where('iscancel', 1)
                ->where('status', 2)
                ->count(),
            'scOrderRefundNum' => $this->dbConn($this->dbOrder)
                ->where('del', 0)
                ->where('iscancel', 2)
                ->count(),
            'scStock' => $scStock,
            'qdStock' => $qdStock,
            'qdShopAuthNum' => $this->dbwbConn($this->dbQdShop)
                ->where('is_check', 0)
                ->count(),
            'qdGoodsNum' => $this->dbwbConn($this->dbQdGoods)
                ->where('del', 0)
                ->count(),
            'qdGsaleNum' => $this->dbwbConn($this->dbQdGoods)
                ->where('del', 0)
                ->where('is_shelf', 1)
                ->count(),
            'qdOrderNum' => $this->dbwbConn($this->dbQdOrder)
                ->where('del', 0)
                ->count(),
            'qdOrderPaynoNum' => $this->dbwbConn($this->dbQdOrder)
                ->where('del', 0)
                ->where('iscancel', 1)
                ->where('status', 1)
                ->count(),
            'qdOrderSendnoNum' => $this->dbwbConn($this->dbQdOrder)
                ->where('del', 0)
                ->where('iscancel', 1)
                ->where('status', 2)
                ->count(),
            'qdOrderRefundNum' => $this->dbwbConn($this->dbQdOrder)
                ->where('del', 0)
                ->where('iscancel', 2)
                ->count(),
        ];
        return $this->toback(0, '', $arys);
    }

    //后台功能列表
    public function getActionIndex($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbAction)
            ->where('del', 0)
            ->where('pid', 0);
        $total = $db->count();
        $res = $db->select('id', 'title', 'link', 'pid')->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有菜单');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $childArys = [];
            $childOnes = DB::table($this->dbAction)
                ->select('id', 'title', 'link', 'pid')
                ->where('del', 0)
                ->where('pid', $v['id'])
                ->get();
            $total ++;
            if (count($childOnes)) {
                foreach ($childOnes as $vv) {
                    $vv = (array) $vv;
                    $childArys[] = [
                        'id' => $vv['id'],
                        'title' => $vv['title'],
                        'link' => $vv['link'],
                        'pid' => $vv['pid'],
                        'pname' => $v['title'],
                    ];
                    $total ++;
                }
            }
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'link' => $v['link'],
                'pid' => 0,
                'pname' => '-',
                'childs' => $childArys,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    //后台功能一个
    public function getActionOne($id)
    {
        $res = (array) DB::table($this->dbAction)
            ->select('id', 'title', 'link', 'pid')
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '没有菜单');
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $res);
    }

    //获取父级
    public function getParent()
    {
        $res = DB::table($this->dbAction)
            ->select('id', 'title')
            ->where('del', 0)
            ->where('pid', 0)
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有菜单');
        }
        $arys[] = [ 'id' => 0, 'title' => '顶层功能' ];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 保存更新
     * @param int $id
     * @param array $pas
     */
    public function actionUpdate($id, $pas)
    {
        $res = (array) DB::table($this->dbAction)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => 'no data');
        }
        $pas['uptime'] = toDate();
        $up = DB::table($this->dbAction)->where('id', $id)->update($pas);
        if (!$up) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 购物车列表
     * @param array $pages【start，limit】
     */
    public function getCartList($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbCart)->where('del', 0);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有商品');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $v['price'] = $v['price'] / 100;
            $v['gimg'] = $v['gimg'] ? env('DOMAIN').'/'.$v['gimg'] : '';
            $arys[] = $v;
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 首页数据看板
     */
    public function indexTongji()
    {
        $start = date('Y-m-d H:i:s', strtotime(date('Ymd', time()).' 00:00:01'));
        $end = date('Y-m-d H:i:s', strtotime(date('Ymd', time()).' 23:59:59'));
        $arys = [
            'today' => [
                'orderNum' => 0, 'saleNum' => 0, 'readNum' => 0,
                'recharge' => 0, 'userNum' => 0,
            ],
            'total' => [
                'orderNum' => 0, 'saleNum' => 0, 'readNum' => 0,
                'recharge' => 0, 'userNum' => 0,
            ],
            'goods' => [],
            'stock' => [],
            'daiban' => [
                'noPayNum' => 0, 'noSendNum' => 0,  'refundNum' => 0,
                'shelfNum' => 0, 'qdAuthNum' => 0,
            ],
            'yujing' => [],
        ];
        //数据看板-流水看板
        $arys['today']['orderNum'] = $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->where('addtime', '>=', $start)
            ->where('addtime', '<=', $end)
            ->count();
        $arys['today']['saleNum'] = $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->where('addtime', '>=', $start)
            ->where('addtime', '<=', $end)
            ->sum('real_pay');
        $arys['today']['saleNum'] = toNumber($arys['today']['saleNum']);
        $arys['today']['readNum'] = $this->dbConn($this->dbUtrace)
            ->where('addtime', '>=', $start)
            ->where('addtime', '<=', $end)
            ->count();
        $arys['today']['recharge'] = $this->dbConn($this->dbPay)
            ->where('type', 1)
            ->where('addtime', '>=', $start)
            ->where('addtime', '<=', $end)
            ->sum('money');
        $arys['today']['recharge'] = toNumber($arys['today']['recharge']);
        $arys['today']['userNum'] = $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('addtime', '>=', $start)
            ->where('addtime', '<=', $end)
            ->count();
        $arys['total']['orderNum'] = $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->count();
        $arys['total']['saleNum'] = $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->sum('real_pay');
        $arys['total']['saleNum'] = toNumber($arys['total']['saleNum']);
        $arys['total']['readNum'] = $this->dbConn($this->dbUtrace)->count();
        $arys['total']['recharge'] = $this->dbConn($this->dbPay)
            ->where('type', 1)
            ->sum('money');
        $arys['total']['recharge'] = toNumber($arys['today']['recharge']);
        $arys['total']['userNum'] = $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->count();
        //数据看板-商品看板
        $goods = $this->dbConn($this->dbGoods)
            ->select('id', 'title')
            ->where('del', 0)
            ->skip(0)->take(5)
            ->orderBy('sale', 'desc')
            ->get();
        if (count($goods)) {
            foreach ($goods as $v) {
                $v = (array) $v;
                $readNum = $this->dbConn($this->dbUtrace)
                    ->where('gid', $v['id'])
                    ->count();
                $orderNum = $this->dbConn($this->dbOsku)
                    ->where('del', 0)
                    ->where('gid', $v['id'])
                    ->sum('num');
                $arys['goods'][] = [
                    'title' => $v['title'],
                    'readNum' => $readNum,
                    'orderNum' => $orderNum,
                ];
            }
        }
        //数据看板-库存看板
        $stocks = $this->dbConn($this->dbGsku)
            ->where('del', 0)
            ->skip(0)->take(5)
            ->orderBy('stock', 'desc')
            ->get();
        if (count($stocks)) {
            foreach ($stocks as $v) {
                $v = (array) $v;
                $gOne = (array) $this->dbConn($this->dbGoods)
                    ->where('id', $v['gid'])
                    ->first();
                $gname = !empty($gOne)&&$gOne['title'] ? $gOne['title'] : '-';
                $arys['stock'][] = [
                    'title' => $gname,
                    'skuName' => $v['title'],
                    'skuNum' => $v['stock'],
                ];
            }
        }
        //数据看板-待办事项
        $arys['daiban']['noPayNum'] = $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->where('iscancel', 1)
            ->where('status', 1)
            ->count();
        $arys['daiban']['noSendNum'] = $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->where('iscancel', 1)
            ->where('status', 2)
            ->count();
        $arys['daiban']['refundNum'] = $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->where('iscancel', 2)
            ->count();
        $arys['daiban']['shelfNum'] = $this->dbConn($this->dbGoods)
            ->where('del', 0)
            ->where('is_shelf', 1)
            ->count();
        $arys['daiban']['qdAuthNum'] = $this->dbwbConn($this->dbQdShop)
            ->where('del', 0)
            ->where('is_check', 0)
            ->count();
        //数据看板-待办事项-零售库存预警
        $skuOnes = $this->dbConn($this->dbGsku)
            ->where('del', 0)
            ->where('stock', '<=', 10)
            ->skip(0)->take(5)
            ->orderBy('stock', 'asc')
            ->get();
        if (count($skuOnes)) {
            foreach ($skuOnes as $v) {
                $v = (array) $v;
                $gOne = (array) $this->dbConn($this->dbGoods)
                    ->where('id', $v['gid'])
                    ->first();
                $gname = !empty($gOne)&&$gOne['title'] ? $gOne['title'] : '-';
                $gno = !empty($gOne)&&$gOne['gno'] ? $gOne['gno'] : '-';
                $arys['yujing'][] = [
                    'gname' => $gname,
                    'gno' => $gno,
                    'skuName' => $v['title'],
                ];
            }
        }
        return $arys;
    }

    /**
     * 财务数据看板
     */
    public function caiwuTongji($rq01, $rq02)
    {
        $arys = [
            'lingshou' => [
                'sell' => 0, 'order' => 0, 'yue' => 0,
                'recharge' => 0, 'card' => 0, 'refund' => 0,
                'tixian' => 0,
            ],
            'lsin' => [
                'sell' => 0, 'shop' => 0,
                'recharge' => 0, 'card' => 0,
            ],
            'lsout' => [
                'sell' => 0, 'tixian' => 0,  'refund' => 0,
            ],
            'qudao' => [
                'sell' => 0, 'yue' => 0,  'recharge' => 0,
                'refund' => 0, 'tixian' => 0,
            ],
            'qdIn' => [
                'total' => 0, 'shop' => 0,  'recharge' => 0,
            ],
            'qdOut' => [
                'total' => 0, 'tixian' => 0,  'refund' => 0,
            ],
        ];
        //零售财务报表
        $arys['lingshou']['sell'] = $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->sum('real_pay');
        $arys['lingshou']['sell'] = toNumber($arys['lingshou']['sell']);
        $arys['lingshou']['order'] = $this->dbConn($this->dbOrder)
            ->where('pay_way', 1)
            ->where('del', 0)
            ->sum('real_pay');
        $arys['lingshou']['order'] = toNumber($arys['lingshou']['order']);
        if ($rq01['end']) {
            $arys['lingshou']['yue'] = $this->dbConn($this->dbUser)
                ->where('del', 0)
                ->where('addtime', '>=', $rq01['start'])
                ->where('addtime', '<=', $rq01['end'])
                ->sum('balance');
        } else {
            $arys['lingshou']['yue'] = $this->dbConn($this->dbUser)
                ->where('del', 0)
                ->sum('balance');
        }
        $arys['lingshou']['yue'] = toNumber($arys['lingshou']['yue']);
        $arys['lingshou']['recharge'] = $this->dbConn($this->dbPay)
            ->where('type', 1)
            ->where('status', 2)
            ->sum('money');
        $arys['lingshou']['recharge'] = toNumber($arys['lingshou']['recharge']);
        $arys['lingshou']['card'] = $this->dbConn($this->dbCardUser)
            ->where('del', 0)
            ->where('from_id', 0)
            ->where('is_transfer', 0)
            ->sum('price');
        $arys['lingshou']['card'] = toNumber($arys['lingshou']['card']);
        $arys['lingshou']['refund'] = $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->where('iscancel', 3)
            ->sum('real_pay');
        $arys['lingshou']['refund'] = toNumber($arys['lingshou']['refund']);
        $arys['lingshou']['tixian'] = $this->dbConn($this->dbUserWithdraw)
            ->where('del', 0)
            ->where('status', 2)
            ->sum('amount');
        $arys['lingshou']['tixian'] = toNumber($arys['lingshou']['tixian']);
        //零售财务报表-零售商城收入总额
        $arys['lsin']['shop'] = $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->where('pay_way', 1)
            ->sum('real_pay');
        $arys['lsin']['recharge'] = $this->dbConn($this->dbPay)
            ->where('type', 1)
            ->where('status', 2)
            ->sum('money');
        $arys['lsin']['card'] = $this->dbConn($this->dbCardUser)
            ->where('del', 0)
            ->where('from_id', 0)
            ->where('is_transfer', 0)
            ->sum('price');
        $arys['lsin']['sell'] = $arys['lsin']['shop'] + $arys['lsin']['recharge'] + $arys['lsin']['card'];
        $arys['lsin']['shop'] = toNumber($arys['lsin']['shop']);
        $arys['lsin']['recharge'] = toNumber($arys['lsin']['recharge']);
        $arys['lsin']['card'] = toNumber($arys['lsin']['card']);
        $arys['lsin']['sell'] = toNumber($arys['lsin']['sell']);
        //零售财务报表-零售商城支出总额
        $arys['lsout']['tixian'] = $this->dbConn($this->dbUserWithdraw)
            ->where('del', 0)
            ->where('status', 2)
            ->sum('amount');
        $arys['lsout']['refund'] = $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->where('iscancel', 3)
            ->sum('real_pay');
        $arys['lsout']['sell'] = $arys['lsout']['tixian'] + $arys['lsout']['refund'];
        $arys['lsout']['tixian'] = toNumber($arys['lsout']['tixian']);
        $arys['lsout']['refund'] = toNumber($arys['lsout']['refund']);
        $arys['lsout']['sell'] = toNumber($arys['lsout']['sell']);
        //渠道财务报表
        if ($rq02['end']) {
            $arys['qudao']['yue'] = $this->dbwbConn($this->dbQdShop)
                ->where('del', 0)
                ->where('addtime', '>=', $rq02['start'])
                ->where('addtime', '<=', $rq02['end'])
                ->sum('balance');
        } else {
            $arys['qudao']['yue'] = $this->dbwbConn($this->dbQdShop)
                ->where('del', 0)
                ->sum('balance');
        }
        $arys['qudao']['recharge'] = $this->dbwbConn($this->dbQdPay)
            ->where('type', 1)
            ->where('status', 2)
            ->sum('money');
        $arys['qudao']['refund'] = $this->dbwbConn($this->dbQdOrder)
            ->where('del', 0)
            ->where('iscancel', 3)
            ->sum('real_pay');
        $arys['qudao']['tixian'] = $this->dbwbConn($this->dbQdTixian)
            ->where('del', 0)
            ->where('status', 2)
            ->sum('amount');
        $arys['qudao']['sell'] = $arys['qudao']['yue'] + $arys['qudao']['recharge']
            + $arys['qudao']['refund'] + $arys['qudao']['tixian'];
        $arys['qudao']['yue'] = toNumber($arys['qudao']['yue']);
        $arys['qudao']['recharge'] = toNumber($arys['qudao']['recharge']);
        $arys['qudao']['refund'] = toNumber($arys['qudao']['refund']);
        $arys['qudao']['tixian'] = toNumber($arys['qudao']['tixian']);
        $arys['qudao']['sell'] = toNumber($arys['qudao']['sell']);
        //渠道财务报表-渠道商城收入总额
        $arys['qdIn']['shop'] = $this->dbwbConn($this->dbQdOrder)
            ->where('del', 0)
            ->where('pay_way', 1)
            ->where('status', '>', 1)
            ->sum('real_pay');
        $arys['qdIn']['recharge'] = $this->dbwbConn($this->dbQdPay)
            ->where('type', 1)
            ->where('status', 2)
            ->sum('money');
        $arys['qdIn']['total'] = $arys['qdIn']['shop'] +$arys['qdIn']['recharge'];
        $arys['qdIn']['shop'] = toNumber($arys['qdIn']['shop']);
        $arys['qdIn']['recharge'] = toNumber($arys['qdIn']['recharge']);
        $arys['qdIn']['total'] = toNumber($arys['qdIn']['total']);
        //渠道财务报表-渠道商城支出总额
        $arys['qdOut']['tixian'] = $this->dbwbConn($this->dbQdTixian)
            ->where('del', 0)
            ->where('status', 2)
            ->sum('amount');
        $arys['qdOut']['refund'] = $this->dbwbConn($this->dbQdOrder)
            ->where('del', 0)
            ->where('iscancel', 3)
            ->sum('real_pay');
        $arys['qdOut']['total'] = $arys['qdOut']['tixian'] +$arys['qdOut']['refund'];
        $arys['qdOut']['tixian'] = toNumber($arys['qdOut']['tixian']);
        $arys['qdOut']['refund'] = toNumber($arys['qdOut']['refund']);
        $arys['qdOut']['total'] = toNumber($arys['qdOut']['total']);
        return $arys;
    }
}